Page({
  data: {
    name: '',
    phone: '',
    postcode: '',
    regionArray: [], // 存储省市区数组
    regionStr: '',   // 存储省市区字符串
    detail: ''
  },

  // 处理地区选择器变化
  handleRegionChange(e) {
    const regionArray = e.detail.value
    this.setData({
      regionArray: regionArray,
      regionStr: regionArray.join(' ')
    })
  },

  openRegionPicker() {
    wx.navigateTo({
      url: '/pages/region-picker/region-picker'
    })
  },

  saveAddress() {
    const { name, phone, postcode, regionStr, detail } = this.data

    if (!name) {
      wx.showToast({
        title: '请输入收货人姓名',
        icon: 'none'
      })
      return
    }

    if (!phone || !/^1\d{10}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }

    if (!regionStr) {
      wx.showToast({
        title: '请选择所在地区',
        icon: 'none'
      })
      return
    }

    // 保存地址时使用
    const newAddress = {
      id: Date.now(),
      name,
      phone,
      address: `${regionStr} ${detail}`,
      postcode
    }

    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2]
    
    // 更新上一页的地址列表
    prevPage.setData({
      addresses: [...prevPage.data.addresses, newAddress]
    })

    wx.navigateBack()
  }
})